package com.ldc.commonres.common

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.launcher.ARouter
import com.ldc.commonres.views.CommonDialogLoading
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope

abstract class FragmentBase : Fragment(), CoroutineScope by MainScope() {

    protected val TAG: String = "【%s】".format(this::class.java.name)

    // 消息处理器
    private val callback = Handler.Callback { p0 -> processMessage(p0) }
    private val handler: Handler = Handler(Looper.getMainLooper(), callback)

    // 对话框
    private var loadDialog: CommonDialogLoading? = null

    // 消息分发
    open fun processMessage(msg: Message): Boolean {
        return true
    }

    // 获取消息处理器
    fun getHandler(): Handler = handler
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        ARouter.getInstance().inject(this)
        loadDialog = CommonDialogLoading(requireActivity())
        val fg: View? = loadLayoutView(inflater, container)
        return fg
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        try {
            start(savedInstanceState)
            main()
        } catch (e: java.lang.Exception) {
            processError(e)
        }
    }

    // 加载视图
    open fun loadLayoutView(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ): View? = null


    open fun start(savedInstanceState: Bundle?) {
        // 开始菜单
    }

    protected abstract fun main()

    open fun processError(e: Exception) {
        e.printStackTrace()
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }


    fun showLoadDialog(str: String = "加载中，请稍等···") {
        loadDialog?.let {
            it.setText(str)
            if (!it.isShowing) {
                it.show()
            }
        }
    }

    fun dismissLoadDialog() {
        loadDialog?.dismiss()
    }
}
